import * as url from 'url';
import * as http from 'http';
import { CommonUtils } from './commonutils';

export class HttpUtils {
    /**
     * 读取http路径的文件
     * @param uri 文件uri
     */
    static readHttpFile(uri: string) {
        console.log(uri);
        return new Promise((resolve, reject) => {
            this.innerReadRemoteData(uri, null, (error, data) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        });
    }
    private static innerReadRemoteData(uri: string, progressCallback?: (progress) => void, callback?: (error, data) => void) {
        const _callback = (error, data?: any) => {
            if (callback) {
                console.log('call callback');
                callback(error, data);
            }
        };
        const _progressCallback = (progress) => {
            if (progressCallback) {
                progressCallback(progress);
            }
        };
        const req = http.get(url.parse(uri), (res) => {
            console.log(`status code:${res.statusCode}`);
            if (res.statusCode !== 200) {
                _callback(`error status:${res.statusCode}`);
                return;
            }
            const data = [];
            let dataLen = 0;
            let totalBytes = 0;
            totalBytes = parseInt(res.headers['content-length'], 10);
            console.log(totalBytes);
            res.on('data', (chunk) => {
                data.push(chunk);
                dataLen += chunk.length;
                const progress = {received: dataLen, rest: totalBytes - dataLen,
                    total: totalBytes, percent: totalBytes > 0 ? dataLen / totalBytes : 0};
                _progressCallback(progress);
                // console.log(`download progress:${JSON.stringify(progress)} bytes`);
            });

            res.on('end', () => {
                _callback(null, Buffer.concat(data));
                console.log(`response end`);
            });
        });

        req.on('error', (err) => {
            _callback(err);
            console.log(`response error:${err}`);
        });
    }
}